import { defineStore } from 'pinia';
import router from '@/router.js';
import axios from 'axios';
import { ElMessage } from 'element-plus';

export const useAuthStore = defineStore("auth", {
  state: () => {
    return {
      user: null,
      // token: ''
    }
  },
  actions: {
    async login(credential) {
      const api = '/api/auth/login';
      try {
        let res = await axios.post(api, {
          username: credential.username,
          password: credential.password
        })
        this.user = res.data;
        // this.token = res.data.token;
        router.push('/students');
      } catch(err) {
        if(err.response) {  // 请求得到响应，但状态码非200
          ElMessage({
            message: '用户名或密码错误',
            type: 'error'
          })
        } else {  // 未成功得到响应
          ElMessage({
            message: '登录失败',
            type: 'error'
          })
        }
        console.error("登录失败。" + err);        
      }      
    },
    logout() {
      this.user = null;
      router.push('/login');
    }
  }
})